package com.size.mall.passport.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.size.mall.mallapi.entity.Member;
import com.size.mall.mallapi.service.MemberService;
import com.size.mall.util.CookieUtil;
import com.size.mall.util.HttpclientUtil;
import com.size.mall.util.JwtUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.hutool.core.util.StrUtil.*;

@Controller
public class PassportController {


    @Reference
    MemberService memberService;


    @RequestMapping("vlogin")
    public String vlogin(String code, HttpServletRequest rq, HttpServletResponse rp) {


        // 换取数据
        String access_url = "https://api.weibo.com/oauth2/access_token?";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("client_id", "3660936033");
        paramMap.put("client_secret", "a41794c7bcde974dea18f9382c2ebf91");
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("redirect_uri", "http://passport.sizemall.com:9040/vlogin");
        paramMap.put("code", code);//
        // 授权有效期内可以使用，没新生成一次授权码，说明用户对第三方数据进行重启授权，之前的access_token和授权码全部过期
        String access_token_json = HttpclientUtil.doPost(access_url, paramMap);

        Map<String, String> access_map = JSON.parseObject(access_token_json, Map.class);


        String access_token = access_map.get("access_token");
        String uid = access_map.get("uid");

        String s4 = "https://api.weibo.com/2/users/show.json?access_token=" + access_token + "&uid=" + uid;
        String user_json = HttpclientUtil.doGet(s4);
        Map<String, String> user_map = JSON.parseObject(user_json, Map.class);


        // 将用户信息保存数据库，用户类型设置为微博用户
        Member umsMember = new Member().
                                               setSourceType("2").
                                               setAccessCode(code).
                                               setAccessToken(access_token).
                                               setSourceUid((String) user_map.get("idstr")).
                                               setCity((String) user_map.get("location")).
                                               setNickname((String) user_map.get("screen_name"));
        String g = "0";
        String gender = (String) user_map.get("gender");
        if (gender.equals("m")) {
            g = "1";
        }
        umsMember.setGender(g);


        String sourceUid = umsMember.getSourceUid();

        List<Member> umsMemberCheck = (List)memberService.listByMap(MapUtil.of("source_id", sourceUid));// 检查该用户(社交用户)
        // 以前是否登陆过系统
        if (umsMemberCheck.isEmpty()) {
            // 都为空说明
            boolean b = memberService.save(umsMember);
        } else {
            umsMember = umsMemberCheck.get(0);
        }

        // 生成jwt的token，并且重定向到首页，携带该token
        String token = null;
        String memberId = umsMember.getId();// rpc的主键返回策略失效
        String nickname = umsMember.getNickname();
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("memberId", memberId);// 是保存数据库后主键返回策略生成的id
        userMap.put("nickname", nickname);

        String ip = rq.getHeader("x-forwarded-for");// 通过nginx转发的客户端ip
        if (isBlank(ip)) {
            ip = rq.getRemoteAddr();// 从request中获取ip
            if (isBlank(ip)) {
                ip = "127.0.0.1";
            }
        }


        // 生成jwt,重定向到首页

        // 按照设计的算法对参数进行加密后，生成token
        token = JwtUtil.encode("2019sizemall", userMap, ip);



        // 将token存入redis一份
        memberService.addUserToken(token, memberId);


        return "redirect:http://yin:8060/index?token="+token;

    }


    @PostMapping("login")
    @ResponseBody
    public String login(Member umsMember, HttpServletRequest request) {
        String token = "";

        // 调用用户服务认证
        Member memberLogin = memberService.login(umsMember);

        if (memberLogin != null) {
            //登陆成功

            // 用jwt制作token
            Map<String, Object> userMap = new HashMap<>();
            String memberId = memberLogin.getId();
            userMap.put("memberId", memberId);
            userMap.put("nickname", memberLogin.getNickname());


            //region 获取客户端的ip  越过nginx
            String ip = request.getHeader("x-forwarded-for"); // nginx 的负载的客户ip
            if (isBlank(ip)) {
                // 没有就是客户机直接访问
                ip = request.getRemoteAddr();
                if (isBlank(ip)) {
                    // 再没有给默认ip
                    ip = "127.0.0.1";

                }
            }

            //endregion

            // 按照设计的算法对数据进行加密
            token = JwtUtil.encode("2019sizemall", userMap, ip);


            // token 存redis一份
            memberService.addUserToken(token, memberId);

        } else {
            token = "fail";
        }


        return token;
    }


    @GetMapping("verify")
    @ResponseBody
    public String verify(String token, String currentIp) {

        // 通过jwt校验token的真假
        Map<String, String> map = new HashMap<>();


        Map<String, Object> decode = JwtUtil.decode(token, "2019sizemall", currentIp);

        if (decode != null) {

            map.put("status", "success");
            map.put("memberId", decode.get("memberId").toString());
            map.put("nickname", (String) decode.get("nickname"));

        } else {
            map.put("status", "fail");
        }


        return JSON.toJSONString(map);
    }

    @RequestMapping("index")
    public String index(String returnUrl, ModelMap modelMap) {

        if (isNotBlank(returnUrl)) {
            modelMap.put("returnUrl", returnUrl);
        }


        return "index";
    }
}
